package com.feityz.provider;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.assign.AssigneeProvider;
import com.bstek.uflo.process.assign.Entity;
import com.bstek.uflo.process.assign.PageQuery;
import com.feityz.system.entity.*;
import com.feityz.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class PtwQtjcProvider implements AssigneeProvider {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IRoleAreaService roleAreaService;
    @Autowired
    private IRoleAreaUserService roleAreaUserService;

    @Override
    public boolean isTree() {
        return false;
    }

    @Override
    public String getName() {
        return "PTW气体检测人员(请在流程变量中传入[AREA]参数";
    }

    @Override
    public void queryEntities(PageQuery<Entity> pageQuery, String parentId) {
        Entity entitie = new Entity("1","气体检测人员");
        List<Entity> ls = new ArrayList<>();
        ls.add(entitie);
        pageQuery.setResult(ls);
        pageQuery.setRecordCount(1);
    }

    /**
     * 按角色取人员
     * @param entityId 处理人ID，可能是一个用户的用户名，这样就是直接返回这个用户名，也可能是一个部门的ID，那么就是返回这个部门下的所有用户的用户名等
     * @param context context 流程上下文对象
     * @param processInstance 流程实例对象
     * @return
     */
    @Override
    public Collection<String> getUsers(String entityId, Context context, ProcessInstance processInstance) {

        Object area = context.getProcessService().getProcessVariable("AREA", processInstance.getId());

        Assert.isTrue(area!=null,"请传入AREA参数");

        //查询部门下area = 传入的辖区
        List<Dept> depts = deptService.lambdaQuery().eq(Dept::getArea,area.toString()).list();

        //查询部门人员
        if(CollectionUtil.isNotEmpty(depts)){

            List<User> users = userService.lambdaQuery()
                    .ne(User::getPosition,"经理")
                    .ne(User::getPosition,"副经理")
                    .in(User::getDept,depts.stream().map(e->e.getId()).collect(Collectors.toList())).list();

            return users.stream().map(e->e.getId().toString()).collect(Collectors.toList());

        }else {
            return new ArrayList<>();
        }
    }

    @Override
    public boolean disable() {
        return false;
    }
}
